/* NOTICE
    OpenJaWS - Open Java Weather Station
    
    Copyright (C) 2008 Grant Gardner <grant@lastweekend.com.au>
    
    OpenJaWS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
NOTICE */

package au.com.lastweekend.openjaws.api;

import java.io.IOException;
import java.io.Serializable;
import java.util.Formattable;
import java.util.FormattableFlags;
import java.util.Formatter;

import au.com.lastweekend.openjaws.units.Unit;

/**
 * Structure for storing a value with the unit it was measured in.
 * 
 * @author ggardner
 * 
 */
public class UnitValue implements Serializable, Formattable, Comparable<UnitValue> {

    public static final UnitValue NULL = new UnitValue();
    private Double value;
    private Unit unit;

    protected UnitValue() {

    }

    public UnitValue(double value, Unit unit) {

        if (unit == null) {
            throw new IllegalArgumentException("unit may not be null");
        }

        this.value = value;
        this.unit = unit;
    }

    public UnitValue convertTo(Unit to) {

        if (to == null || value == null || unit == null) {
            return NULL;
        }

        return to.equals(unit) ? this : new UnitValue(to.convertFrom(value, unit), to);
    }

    public Double getValue() {

        return value;
    }

    public Unit getUnit() {

        return unit;
    }

    public String toString() {

        return format("%s");
    }

    public String format(String formatSpec) {

        return String.format(formatSpec, this);
    }

    public int compareTo(UnitValue o) {

        if (this.unit == null || o.unit == null) {
            throw new NullPointerException("Cannot compare nulls " + this + ".compareTo(" + o + ")");
        }

        if (o == this) {
            return 0;
        } else {
            return this.value.compareTo(this.unit.convertFrom(o.value, o.unit));
        }
    }

    @Override
    public boolean equals(Object obj) {

        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final UnitValue other = (UnitValue) obj;
        if (unit == null) {
            if (other.unit != null)
                return false;
        } else if (!unit.equals(other.unit))
            return false;
        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        return true;
    }

    @Override
    public int hashCode() {

        final int prime = 61;
        int result = 1;
        result = prime * result + ((unit == null) ? 0 : unit.hashCode());
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

    public void formatTo(Formatter formatter, int flags, int width, int precision) {

        boolean alternate = (flags & FormattableFlags.ALTERNATE) == FormattableFlags.ALTERNATE;
        // boolean upper = (flags & FormattableFlags.UPPERCASE) == FormattableFlags.UPPERCASE;
        boolean leftJustify = (flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY;

        // Let's try and ignore the rules and use precision for precision.

        String unitString;
        String valueString;
        if (unit == null || value == null) {
            unitString = "null";
            valueString = "";
            width = width - 4;
        } else {

            unitString = (alternate ? " " : "") + getFormatNonValuePart();

            width = width - unitString.length();

            String valueFormat = "%f";
            if (precision >= 0) {
                valueFormat = "%." + precision + "f";
            }

            valueString = String.format(valueFormat, value);

            width = width - valueString.length();
        }

        try {
            Appendable appendable = formatter.out();
            if (leftJustify) {
                appendable.append(valueString);
                appendable.append(unitString);
            }

            while (width > 0) {
                appendable.append(' ');
                width--;
            }

            if (!leftJustify) {
                appendable.append(valueString);
                appendable.append(unitString);
            }
        } catch (IOException e) {
            // What the !#$ are we supposed to do here...
            throw new RuntimeException("Exception during format", e);
        }

    }

    /**
     * Hack to support WindUnitValue
     * 
     * @return the non value part of the formatted string
     */
    protected String getFormatNonValuePart() {

        return String.format("%s", unit);
    }

    public UnitValue add(UnitValue operand) {
        if (isNull()) {
            return operand;
        }
        
        if (operand.isNull()) {
            return this;
        }
        
        double newValue = value + operand.convertTo(getUnit()).getValue();
        return new UnitValue(newValue, getUnit());

    }

    public boolean isNull() {

        return this == NULL;
    }

}
